<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    width="400px"
  >
    <!-- status-icon 当表单校验不通过时, 输入框右侧有个 x 小图标 -->
    <el-form
      status-icon
      ref="formDataRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
      style="width: 300px"
    >
      <el-form-item label="标签名称:" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="分类名称:" prop="categoryId">
        <el-select v-model="formData.categoryId" clearable filterable>
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('formData')" size="mini">
          确定</el-button
        >
        <el-button size="mini" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { ApiAdd, ApiUpId } from '@/api/label'
export default {
  props: {
    categoryList: { //所有正常状态的分类
      type: Array,
      default: []
    },
    dialogVisible: { // 弹窗控制
      type: Boolean,
      default: false
    },
    formData: { // 表单数据
      type: Object,
      default: {}
    },
    title: {
      type: String,
      default: ''
    },
    remoteForm: Function // 关闭弹窗
  },
  data () {
    return {
      rules: { // 校验规则
        name: [ // 与 el-form-item 标签的 prop 属性值对应
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请输入分类名称', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    handleClose () { // 关闭弹框
      this.$refs['formDataRef'].resetFields()
      this.remoteForm()
    },
    submitForm () { // 提交表单数据
      this.$refs['formDataRef'].validate(valid => {
        if (!valid) {
          return false
        }
        this.submitData()
      })
    },
    async submitData () { //校验成功的方法
      let res = null
      if (this.formData.id) { // id存在编辑操作
        res = await ApiUpId(this.formData)
      } else { // 否则新增操作
        res = await ApiAdd(this.formData)
      }
      if (res.code === 20000) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.handleClose()
      } else {
        this.$message({
          message: '保存失败',
          type: 'error'
        })
      }
    }
  },
}
</script>

<style>
</style>